const express = require('express')
const router = express.Router()
//五.
const user = require('../modle/user')
const classify = require('../modle/classify')
const shop = require('../modle/shop')
//5.
const JWT = require('../tools/jwt')

router.post('/login', (req, res) => {
    const { username, password } = req.body
    user.find({ username }).then(data => {
        if (data.length) {
            if (data[0].password == password) {
                //6.
                const token = JWT.generate(req.body, '10h')
                res.cookie('token', token, {
                    maxAge: 1000 * 60 * 60 * 10
                })
                res.send('登录成功')
            } else {
                res.send('密码错误')
            }
        } else {
            user.create({
                username,
                password
            })
            const token = JWT.generate(req.body, '10h')
            res.cookie('token', token, {
                maxAge: 1000 * 60 * 60 * 10
            })
            res.send('注册并登录成功')
        }
    })
})

router.get('/getClassify', (req, res) => {
    classify.find().then(data => {
        res.send(data)
    }).catch(err=>{
        console.log(err);
    })
})

router.post('/classify', (req, res) => {
    const { classifyAdd, icon } = req.body
    classify.create({
        classify: classifyAdd,
        icon
    })
})

router.get('/getShop', (req, res) => {
    shop.find({}).then(data => {
        res.send(data)
    })
})

module.exports = router